package com.suntront.module_datasynch.taskdown

import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.widget.EditText
import androidx.lifecycle.rxLifeScope
import com.mtjsoft.www.kotlinmvputils.base.BaseRecycleViewModel
import com.mtjsoft.www.kotlinmvputils.imp.AndCallBackListImp
import com.mtjsoft.www.kotlinmvputils.model.LoadState
import com.mtjsoft.www.kotlinmvputils.rxhttp.RxUrl
import com.mtjsoft.www.kotlinmvputils.rxhttp.error.code
import com.mtjsoft.www.kotlinmvputils.rxhttp.error.msg
import com.suntront.lib_db.AppDatabase
import com.suntront.lib_db.table.MeterT
import com.suntront.lib_db.table.MeterTDownLoadUpdate
import com.suntront.lib_db.table.UserT
import com.suntront.module_datasynch.model.TaskDownModel
import com.suntront.module_datasynch.model.UserResponse
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.toResponse

/**
 * @author mtj
 * @Package com.suntront.module_datasynch.taskdown
 * @date 2020-05-26 10:28:33
 */

class TaskDownViewModel : BaseRecycleViewModel<TaskDownModel>() {

    val adminId = MMKV.defaultMMKV().getString("AdminID", "")
    val adminName = MMKV.defaultMMKV().getString("AdminName", "")

    var keyword = ""

    /**
     * 获取列表数据
     */
    override fun getListDataInThread(
        pager: Int,
        callBackListImp: AndCallBackListImp<TaskDownModel>
    ) {
        // 开启协程，先从本地数据库获取
        rxLifeScope.launch({
            // 异步读取本地数据库
            val list: MutableList<MeterT> = async {
                AppDatabase.getDb().meterDao()
                    .queryMeterTsByAdminId(adminId)
            }.await()
            if (list.size > 0) {
                val data: MutableList<TaskDownModel> = ArrayList()
                for (item in list) {
                    val model = TaskDownModel()
                    model.id = item.id
                    model.rosterId = item.rosterId
                    model.rosterName = item.rosterName
                    model.rosterCode = item.rosterCode
                    model.isLoad = item.isLoad
                    model.adminID = item.adminId
                    model.adminName = item.adminName
                    data.add(model)
                }
                callBackListImp.onSuccess(data)
            } else {
                // 从网络获取数据
                //通过launch方法开启一个协程
                val data = RxHttp.postJson(RxUrl.DOWNLOAD_ROSTER)
                    .add("MeterReaderId", adminId)
                    .toResponse<List<TaskDownModel>>()
                    .await()
                val meterTs: MutableList<MeterT> = ArrayList()
                // 在协程中异步处理
                val longids = async {
                    for (item in data) {
                        val model = MeterT()
                        model.rosterId = item.rosterId
                        model.rosterName = item.rosterName
                        model.rosterCode = item.rosterCode
                        model.adminId = adminId!!.toInt()
                        model.adminName = adminName
                        model.isLoad = false
                        meterTs.add(model)
                    }
                    AppDatabase.getDb().meterDao().insertMeters(meterTs)
                }.await()
                // 存入成功,更换id
                for (i in data.indices) {
                    data[i].id = longids[i].toInt()
                }
                callBackListImp.onSuccess(data)
            }
        }, {
            //异常回调，这里的it为Throwable类型
            val code = it.code
            val msg = it.msg
            showToastUI(msg)
            loadState.postValue(LoadState.NODATA)
        })
    }

    /**
     * 监听搜索词输入
     */
    fun setKeyWord(et: EditText) {
        et.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable) {
                keyword = s.toString()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
    }

    /**
     * 搜索
     */
    fun search() {
        if (keyword == "") {
            showToastUI("请输入册本名称")
            return
        }
        rxLifeScope.launch({
            // 开启协程，异步获取数据
            val listMeterT: MutableList<MeterT> = async {
                AppDatabase.getDb().meterDao()
                    .queryMeterTsByAdminIdAndRosterName(adminId, "%$keyword%")
            }.await()
            val data: MutableList<TaskDownModel> = ArrayList()
            if (listMeterT.size > 0) {
                for (item in listMeterT) {
                    val model = TaskDownModel()
                    model.rosterId = item.rosterId
                    model.rosterName = item.rosterName
                    model.rosterCode = item.rosterCode
                    model.isLoad = item.isLoad
                    model.adminID = item.adminId
                    model.adminName = item.adminName
                    data.add(model)
                }
            }
            isSwipeRefresh.value = true
            list.value = data
            temp.value = data
        }, {
            showToastUI(it.msg)
        })
    }

    /**
     * 下载册本
     */
    fun download() {
        val rosterIds = StringBuilder()
        val rosterAllSize = HashMap<Int, Int>()
        val rosterCopySize = HashMap<Int, Int>()
        val choosePosition = HashMap<Int, Int>()
        for (i in list.value!!.indices) {
            if (!list.value!![i].isLoad && list.value!![i].isChoose) {
                choosePosition[i] = list.value!![i].rosterId
                rosterIds.append(list.value!![i].rosterId)
                rosterIds.append(",")
            }
        }
        if (rosterIds.isEmpty()) {
            showToastUI("请选择要下载的表册")
            return
        }
        rosterIds.deleteCharAt(rosterIds.lastIndex)
        rxLifeScope.launch({
            //通过launch方法开启一个协程
            val users = RxHttp.postJson(RxUrl.DOWNLOAD_USER)
                .addAll("{\"RosterIds\":[$rosterIds]}")
                .toResponse<List<UserResponse>>()
                .await()
            val userTs: MutableList<UserT> = ArrayList()
            for (user in users) {
                if (rosterAllSize.containsKey(user.rosterID)) {
                    rosterAllSize[user.rosterID] = rosterAllSize[user.rosterID]!! + 1
                } else {
                    rosterAllSize[user.rosterID] = 1
                }
                val userT = UserT()
                userT.rosterId = user.rosterID
                userT.rosterCode = user.rosterCode
                userT.rosterName = user.rosterName
                userT.addFlow = user.addFlow
                userT.arrearsCount = user.arrearscount
                userT.currNumber = user.currNum
                userT.currWaterNumber = user.currWaterNum
                userT.lastNumber = user.lastNumber
                userT.meterCode = user.meterCode
                userT.meterInfoId = user.meterInfoID
                userT.meterWallAddress = user.meterWallAddress
                userT.mixWaterFlow = user.mixwaterflow
                userT.mixWaterType = user.mixwatertype
                userT.sumMoney = user.sumMoney
                userT.arrearsCount = user.arrearscount
                userT.threeAverage = user.avgCurrenttraffic
                userT.userAddress = user.userAddress
                userT.userInfoCode = user.userInfoCode
                userT.userInfoId = user.userInfoID
                userT.userName = user.userName
                userT.userState = user.userstate
                userT.ismakebill = user.ismakebill
                userT.userWaterTypeName = user.usewatertypename
                userT.year = user.dataYear
                userT.month = user.dataMonth
                userT.sealNumber = user.sealInt
                userT.rosterOrder = user.rosterOrder
                userT.wellId = user.wellID
                userT.wellName = user.wellName
                userT.contect = user.contect
                if (user.currNum > 0) {
                    userT.isDown = true
                    userT.writeMeterState = 1 //已抄
                    if (rosterCopySize.containsKey(user.rosterID)) {
                        rosterCopySize[user.rosterID] = rosterCopySize[user.rosterID]!! + 1
                    } else {
                        rosterCopySize[user.rosterID] = 1
                    }
                } else {
                    userT.isDown = false
                    userT.writeMeterState = 2 //未抄
                }
                userT.upLoad = false
                userT.upUserInfo = false
                userT.meterDataCurrentMonthId = user.meterdatacurrentmonthid
                userT.setMark(user.remark)
                userT.sealNumber = user.sealcode
                userT.userType = user.usertype
                if (TextUtils.isEmpty(user.metercal)) {
                    userT.metercal = 0
                } else {
                    userT.metercal = user.metercal.toInt()
                }
                userTs.add(userT)
            }
            if (userTs.size > 0) {
                async(Dispatchers.IO) {
                    AppDatabase.getDb().userDao().insertUsers(userTs)
                    // 保存成功，修改册本信息
                    val meterTDownLoadUpdateList: MutableList<MeterTDownLoadUpdate> = ArrayList()
                    for (key in choosePosition.keys) {
                        val meterTDownLoadUpdate = MeterTDownLoadUpdate()
                        meterTDownLoadUpdate.id = list.value!![key].id
                        meterTDownLoadUpdate.rosterId = choosePosition[key]!!
                        meterTDownLoadUpdate.userCount =
                            if (rosterAllSize.containsKey(meterTDownLoadUpdate.rosterId)) rosterAllSize[meterTDownLoadUpdate.rosterId]!! else 0
                        meterTDownLoadUpdate.copyCount =
                            if (rosterCopySize.containsKey(meterTDownLoadUpdate.rosterId)) rosterCopySize[meterTDownLoadUpdate.rosterId]!! else 0
                        meterTDownLoadUpdate.unCopyCount =
                            meterTDownLoadUpdate.userCount - meterTDownLoadUpdate.copyCount
                        meterTDownLoadUpdate.isLoad = meterTDownLoadUpdate.userCount > 0
                        meterTDownLoadUpdateList.add(meterTDownLoadUpdate)
                        list.value!![key].isLoad = meterTDownLoadUpdate.userCount > 0
                        list.value!![key].isChoose = false
                    }
                    AppDatabase.getDb().meterDao().updateMetesDownLoad(meterTDownLoadUpdateList)
                    withContext(Dispatchers.Main) {
                        showToastUI("下载成功")
                        // 刷新
                        notifyDataSetChanged()
                    }
                }
            } else {
                showToastUI("该册本下无用户数据")
            }
        }, {
            //异常回调，这里的it为Throwable类型
            val code = it.code
            val msg = it.msg
            showToastUI(msg)
        }, {
            showLoadingUI("正在加载...", false)
        }, {
            hideLoadingUI()
        })
    }
}